package com.byxy.student.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.byxy.student.entity.UploadFile;
import com.byxy.student.service.UploadFileService;
import com.opensymphony.xwork2.ActionSupport;

public class StudentFileAction extends ActionSupport {
	@Autowired
	private UploadFileService fileService;
	private File file;
	private String fileFileName;
	private String fileContentType;
	private Integer id;
	private String downFileName;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getDownFileName() {
		return downFileName;
	}

	public void setDownFileName(String downFileName) {
		this.downFileName = downFileName;
	}

	public String upload() throws IOException {
		// 获取文件上传路径
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		// 创建一个目标文件用来保存
		File destFile = new File(path, fileFileName);
		// 保存文件到数据库
		UploadFile sf = new UploadFile();
		sf.setName(getFileFileName());
		sf.setPath(destFile.getPath());
		fileService.addFile(sf);
		// 把上传的文件，拷贝到目标文件中
		FileUtils.copyFile(file, destFile);
		return SUCCESS;
	}

	public String fileList() throws Exception {
		ServletActionContext.getRequest().getSession().setAttribute("list", fileService.findFileList());
		return SUCCESS;
	}

	public String down() throws UnsupportedEncodingException {
		this.downFileName = fileService.findFileById(id).getName();
		downFileName = new String(downFileName.getBytes("gbk"), "ISO-8859-1");
		return SUCCESS;
	}

	public InputStream getInput() throws FileNotFoundException {
		return new FileInputStream(fileService.findFileById(id).getPath());
	}
}
